// pages/item-detail/item-detail.js
const api = require('../../utils/request.js');
const RATE_MAP = {
  1: '不忍直视',
  2: '很差',
  3: '差',
  4: '较差',
  5: '无过无失',
  6: '还行',
  7: '推荐',
  8: '力荐',
  9: '神作',
  10: '超神作'
};


Page({

  /**
   * 页面的初始数据
   */
  data: {
    popupShow: false,
    loading: true, // 控制骨架屏的显示与隐藏
    subject: null, // 条目详情
    errMsg: '',
    collectionData: {}, // 收藏状态
    episodes: null, // 章节列表
    tags: null, // 标签列表
    staff: null, // 制作人员列表
    weekdayText: '',
    watchedCount: 0, // 已观看的集数
    totalCount: 0,   // 总集数
    ratingBarHeights: [], // 每个评分等级的柱状图高度
    scoreInfo: '',
    username: '',
    collectionStatusMap: [
      '收藏',
      '想看',
      '看过',
      '在看',
      '搁置',
      '弃置'
    ],
    characters: [], // 角色列表
    default_image_url: 'https://tse1-mm.cn.bing.net/th/id/OIP-C.28G3L2JDuwXQGE2pQRDkKQHaHL?w=186&h=180&c=7&r=0&o=5&cb=thvnext&dpr=1.9&pid=1.7',
    // 新增部分加载状态和错误状态
    subjectLoading: true,
    subjectError: false,
    episodesLoading: true,
    episodesError: false,
    charactersLoading: true,
    charactersError: false,
    staffLoading: true,
    staffError: false
  },

  onLoad: function (options) {
    console.log(options);
    const subjectId = options.id;
    // const subjectId = 509986;//待改
    this.loadSubjectData(subjectId);
    this.getEpisodeInfo(subjectId);
    this.getStaffInfo(subjectId);
    this.getCharactersInfo(subjectId);
  },

  // 跳转到通用列表页
  jumpToList: function (e) {
    const id = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type; // 'character' 或 'person'
    console.log(`/pages/list/list?id=${id}&type=${type}`);
    wx.navigateTo({
      url: `/pages/list/list?id=${id}&type=${type}`,
    });
  },

  // 跳转到通用详情页
  jumpToDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type; // 'character' 或 'person'
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}&type=${type}`,
    });
  },

  // 显示收藏状态弹窗
  showCollectionPopup(e) {
    // this.loadCollectionSubjectData(this.data.subject.id)
    console.log(this.data.subject);
    api.postUserCollection(this.data.subject.id);
    this.setData({
      // collectionData: itemData,
      popupShow: true
    });
  },

  // 隐藏收藏状态弹窗
  hideCollectionPopup() {
    this.setData({
      popupShow: false
    });
  },

  // // 映射收藏状态
  // mapCollectionType(type) {
  //   const map = {
  //     1: 'wish',
  //     2: 'collect',
  //     3: 'doing',
  //     4: 'on_hold',
  //     5: 'dropped'
  //   };
  //   return map[type] || 'default';
  // },

  // // 反向映射收藏状态
  // reverseMapCollectionType(type) {
  //   const map = {
  //     'wish': 1,
  //     'collect': 2,
  //     'doing': 3,
  //     'on_hold': 4,
  //     'dropped': 5
  //   };
  //   return map[type] || 0;
  // },

  async loadCollectionSubjectData(subjectId) {
    api.getUserCollection(this.data.username, subjectId)
      .then((res) => {
        const collectionData = {
          comment: res.comment || '',
          private: res.private,
          type: res.type,
          rate: res.rate,
          subject_id: res.subject_id,
          subject_type: res.subject_type,
          tags: res.tags,
          updated_at: res.updated_at,
          vol_status: res.vol_status
        };
        this.setData({
          collectionData: collectionData
        })
      })

      .catch((err) => {
        console.error('Error loading episodes:', err);
      });
  },
  // 更新收藏状态
  async updateCollectionStatus(e) {
    const formData = e.detail.formData;
    try {
      const payload = {
        type: formData.collection.number,
        rate: formData.ratingScore,
        comment: formData.roast,
        private: formData.isPrivate
      };
      await api.postUserCollection(this.data.collectionData.subject_id, payload);
      const collectionData = this.data.collectionData;
      collectionData.type = formData.collection.number,
        collectionData.rate = formData.ratingScore,
        collectionData.comment = formData.roast,
        collectionData.private = formData.isPrivate
      this.setData({
        collectionData: collectionData
      });

      console.log(this.data.collectionData);
      this.hideCollectionPopup();

      // 显示操作成功提示
      const statusMap = {
        'wish': '想看',
        'collect': '看过',
        'doing': '在看',
        'on_hold': '搁置',
        'dropped': '弃置'
      };

      wx.showToast({
        title: '成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('更新收藏状态失败:', error);
      wx.showToast({
        title: '更新收藏状态失败',
        icon: 'none'
      });
    }
  },

  // 加载条目数据
  loadSubjectData(subjectId) {
    this.setData({
      subjectLoading: true,
      subjectError: false
    });
    api.getSubjectById(subjectId)
      .then((res) => {
        const processedInfobox = this.processInfobox(res.infobox);
        this.setData({
          username: wx.getStorageSync('username'),
          subject: {
            ...res,
            infobox: processedInfobox
          },
          scoreInfo: RATE_MAP[Math.round(res.rating.score)] || '',
          loading: false,
          subjectLoading: false,
          ratingBarHeights: this.calculateRatingBarHeights(res.rating.count)
        });
        this.loadCollectionSubjectData(subjectId);
      })
      .catch((err) => {
        console.error('Error loading subject data:', err);
        this.setData({
          errMsg: err.message,
          loading: false,
          subjectLoading: false,
          subjectError: true
        });
      });
  },

  // 获取章节信息
  getEpisodeInfo(subjectId) {
    this.setData({
      episodesLoading: true,
      episodesError: false
    });
    api.getUserSubjectEpisodeCollection(subjectId)
      .then((res) => {
        this.setData({
          episodes: res.data,
          episodesLoading: false
        });
      })
      .catch((err) => {
        console.error('Error loading episodes:', err);
        this.setData({
          episodesLoading: false,
          episodesError: true
        });
      });
  },

  // 获取角色信息
  getCharactersInfo(subjectId) {
    this.setData({
      charactersLoading: true,
      charactersError: false
    });
    api.getSubjectCharacters(subjectId)
      .then((res) => {
        this.setData({
          characters: res,
          charactersLoading: false
        });
      })
      .catch((err) => {
        console.error('Error loading characters:', err);
        this.setData({
          charactersLoading: false,
          charactersError: true
        });
      });
  },

  // 获取制作人员信息
  getStaffInfo(subjectId) {
    this.setData({
      staffLoading: true,
      staffError: false
    });
    api.getSubjectPersons(subjectId)
      .then((res) => {
        this.setData({
          staff: res,
          staffLoading: false
        });
      })
      .catch((err) => {
        console.error('Error loading staff:', err);
        this.setData({
          staffLoading: false,
          staffError: true
        });
      });
  },

  // 预处理 infobox 数据，添加类型判断结果
  processInfobox(infobox) {
    return infobox.map(item => {
      const value = item.value;
      let type = '';
      if (typeof value === 'string') {
        type = 'string';
      } else if (Array.isArray(value)) {
        type = 'array';
      } else {
        type = 'other';
      }
      return {
        ...item,
        valueType: type
      };
    });
  },

  // 辅助方法：根据评分数据计算柱状图高度
  calculateRatingBarHeights(ratingCounts) {
    if (!ratingCounts) return Array(10).fill(0);
    const maxCount = Math.max(...Object.values(ratingCounts));
    if (maxCount <= 0) return Array(10).fill(0);
    return Array.from({ length: 10 }, (_, index) => {
      const rating = index + 1;
      const count = ratingCounts[rating] || 0;
      return (count / maxCount) * 100;
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})